package com.yonyou.iuap.corp.demo.api.V1;

import com.alibaba.fastjson.JSON;
import com.yonyou.iuap.corp.demo.utils.RequestTool;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author nishch
 * @version 3.0
 * @date 2020/3/11
 * @des  自建应用token
 */
@Slf4j
@Component
public class BaseApi {

    private final Logger log = LoggerFactory.getLogger(getClass());

    //自建应用token
    @Autowired
    private  SelfBuildToken token;

    public  String doGet(String requestUrl, Map<String, Object> paramMap) throws Exception {
        String url = getUrl(requestUrl);
        String result =  RequestTool.doGet(url,paramMap,false);
        log.info(result);
        return result;
    }

    public  String  doPostByUserToken(String requestUrl, Map<String, Object> paramMap) throws Exception {
        String url = getUrl(requestUrl);
        if(paramMap==null) {
            paramMap = new HashMap<String, Object>();
        }
        String result =RequestTool.doPostByUserToken(url, paramMap);
        log.info(result);
        return result;
    }

    public  String doGetByUserToken(String requestUrl, Map<String, Object> paramMap) throws Exception {
        String result =  RequestTool.doGet(requestUrl,paramMap,true);
        log.info(result);
        return result;
    }

    public  String  doPost(String requestUrl, Map<String, Object> paramMap) throws Exception {
        requestUrl = getUrl(requestUrl);
        if(paramMap==null) {
            paramMap = new HashMap<String, Object>();
        }
        String result =RequestTool.doPost(requestUrl, paramMap);
        log.info(result);
        return result;
    }

    public  String  doPostOther(String requestUrl, Map<String, Object> paramMap) throws Exception {
        if(paramMap==null) {
            paramMap = new HashMap<String, Object>();
        }
        String result =RequestTool.doPost(requestUrl, paramMap);
        log.info(result);
        return result;
    }

    public  String  doPostJson(String requestUrl, String jsonStr) throws Exception {
        requestUrl = getUrl(requestUrl);
        String result =RequestTool.doPostJson(requestUrl,JSON.toJSONString(JSONObject.fromObject(jsonStr)));
        log.info(result);
        return result;
    }

    /**
     * 自建应用拼装token
     * @param requestUri
     * @return
     * @throws Exception
     */
    protected  String getUrl(String requestUri) throws Exception {
        String access_token = token.createToken();
        return requestUri+"?access_token="+access_token;
    }



}
